package cn.minsh.lims.eoms.modules.job.task;

import cn.minsh.lims.eoms.modules.app.entity.InspectionPlanEntity;
import cn.minsh.lims.eoms.modules.app.enums.PlanStatusEnum;
import cn.minsh.lims.eoms.modules.app.service.InspectionPlanService;
import cn.minsh.lims.eoms.modules.app.utils.LocalDateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 检查计划时间，修改状态
 * 检查计划状态：检查为开始和已开始状态的数据
 * 1、如果当前日期不早于首次开始时间，计划从未开始-》进行中
 * 2、如果失效时间不晚于当日时间，计划从进行中-》已结束
 * @author Administrator
 */
@Component("checkInspectionPlanStatusTask")
public class CheckInspectionPlanStatusTask implements ITask{

    @Autowired
    private InspectionPlanService inspectionPlanService ;


    @Override
    public void run(String params) {
        QueryWrapper<InspectionPlanEntity> queryWrapper = new QueryWrapper() ;
        List<Integer> statusList = new ArrayList<>() ;
        statusList.add(PlanStatusEnum.NOT_STARTED.getCode()) ;
        statusList.add(PlanStatusEnum.STARTED.getCode()) ;
        queryWrapper.in("status",statusList) ;
        List<InspectionPlanEntity> list = inspectionPlanService.list(queryWrapper) ;

        List<InspectionPlanEntity> updateList = new ArrayList<>() ;
        if (!CollectionUtils.isEmpty(list)){
            //检查时间段
            list.stream().forEach(e->{
                //未关闭订单关闭
                if (e.getInvalidTime() != null && new Date().after(e.getInvalidTime())){
                    //结束
                    InspectionPlanEntity planEntity = new InspectionPlanEntity() ;
                    planEntity.setId(e.getId());
                    planEntity.setStatus(PlanStatusEnum.OVER.getCode());
                    updateList.add(planEntity) ;
                    return;
                }

                if (PlanStatusEnum.NOT_STARTED.getCode().equals(e.getStatus())){
                    //判断首次开始时间
                    try {
                        if (LocalDateUtils.getDayCount(new Date(),e.getFirstStartTime())>-1){
                            InspectionPlanEntity planEntity = new InspectionPlanEntity() ;
                            planEntity.setId(e.getId());
                            planEntity.setStatus(PlanStatusEnum.STARTED.getCode());
                            updateList.add(planEntity) ;
                        }
                    } catch (ParseException parseException) {
                        parseException.printStackTrace();
                    }
                }
            });
            inspectionPlanService.updateBatchById(updateList) ;
        }
    }
}
